package com.finger.forest.fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.finger.forest.R;
import com.finger.forest.adapter.CollectionResourceAdapter;
import com.finger.forest.adapter.FireInfoAdapter;
import com.finger.forest.base.BaseFragment;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.CollectionResourceModel;
import com.finger.forest.model.CollectionRoadModel;
import com.finger.forest.model.FireInfoModel;
import com.finger.forest.model.ResourceModel;
import com.finger.forest.model.ResourceTypeModel;
import com.finger.forest.utils.StringUtil;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.UniversalItemDecoration;
import com.finger.forest.utils.encode.PrefsUtil;
import com.jakewharton.rxbinding2.view.RxView;

import org.litepal.LitePal;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 数据同步-资源
 */
public class ReourceFragment extends BaseFragment<RegisterPresenter> implements BaseView {

    private Unbinder unbinder;

    @BindView(R.id.rvData)
    RecyclerView rvData;

    @BindView(R.id.tvAllSynchronization)
    TextView tvAllSynchronization;

    private List<CollectionResourceModel> collectionResourceModels = new ArrayList<>();

    private CollectionResourceAdapter collectionResourceAdapter;

    private int resourceId = 0;

    @Override
    protected void receiveData() {

    }

    @Override
    protected void initializeNavigation() {

    }

    @Override
    protected void initializeView() {
        List<CollectionResourceModel> collectionResourceModelList = LitePal.findAll(CollectionResourceModel.class, true);
        collectionResourceModels.clear();
        collectionResourceModels.addAll(collectionResourceModelList);
        if (null != collectionResourceModels && collectionResourceModels.size() > 0) {
            collectionResourceAdapter = new CollectionResourceAdapter(R.layout.synchronization_data_item_view, collectionResourceModels);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            rvData.setLayoutManager(linearLayoutManager);
            rvData.setAdapter(collectionResourceAdapter);
            rvData.addItemDecoration(new UniversalItemDecoration() {
                @Override
                public Decoration getItemOffsets(int position) {
                    ColorDecoration colorDecoration = new ColorDecoration();
                    colorDecoration.bottom = getResources().getDimensionPixelOffset(R.dimen.dp_1);
                    colorDecoration.decorationColor = getResources().getColor(R.color.blackF5);
                    return colorDecoration;
                }
            });
            collectionResourceAdapter.notifyDataSetChanged();
        }

        clicks();
    }

    @Override
    protected void loadDataFromServer() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_reource, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    private void clicks() {
        //保存
        RxView.clicks(tvAllSynchronization).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            for (CollectionResourceModel collectionRoadModel : collectionResourceModels) {
                if (collectionRoadModel.isSelect()) {
                    resourceId = collectionRoadModel.getId();
                    uploadResource(collectionRoadModel);
                    break;
                }
            }
        });
    }

    private void uploadResource(CollectionResourceModel collectionRoadModel) {
        Map<String, RequestBody> bodyMap = new HashMap<>();
        bodyMap.put("resourceTypeId", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"),
                collectionRoadModel.getResourceCollection() == null ? "0" : collectionRoadModel.getResourceCollection().getResourceTypeId() + ""));
        bodyMap.put("longitude", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), ""
                + collectionRoadModel.getResourceCollection().getLongitude()));
        bodyMap.put("latitude", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), ""
                + collectionRoadModel.getResourceCollection().getLatitude()));
        bodyMap.put("name", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), collectionRoadModel.getResourceCollection().getName()));
        bodyMap.put("remark", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), collectionRoadModel.getResourceCollection().getRemark()));
        bodyMap.put("createUser", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), userId + ""));

        //封装图片集合
        List<MultipartBody.Part> listFile = new ArrayList<>();
        for (int i = 0; i < collectionRoadModel.getImageUrl().size(); i++) {
            String filePath_ = collectionRoadModel.getImageUrl().get(i);
            File fileTemp = new File(filePath_);
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), fileTemp);
            MultipartBody.Part requestImgPart =
                    MultipartBody.Part.createFormData("imageFile",
                            filePath_.substring(filePath_.lastIndexOf("/") + 1, filePath_.length()), requestFile);
            listFile.add(requestImgPart);
        }

        //封装语音集合
        List<MultipartBody.Part> listFileVoice = new ArrayList<>();
        for (int i = 0; i < collectionRoadModel.getVoiceUrl().size(); i++) {
            String filePath_ = collectionRoadModel.getVoiceUrl().get(i);
            File fileTemp = new File(filePath_);
            RequestBody requestFile = RequestBody.create(MediaType.parse("audio/PCMA"), fileTemp);
            MultipartBody.Part requestImgPart =
                    MultipartBody.Part.createFormData("voiceFile",
                            filePath_.substring(filePath_.lastIndexOf("/") + 1, filePath_.length()), requestFile);
            listFileVoice.add(requestImgPart);
        }

        //非离线
        showPd();
        presenter.uploadResource(bodyMap, listFile, listFileVoice);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != unbinder) {
            unbinder.unbind();
        }
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            case ResponseTag.UPLOAD_RESOURCE:
                CollectionResourceModel collectionResourceModel = (CollectionResourceModel) model;
                if (null != collectionResourceModel) {
                    //同步成功数据库删除
                    LitePal.delete(CollectionResourceModel.class, resourceId);

                    //显示的数据也清除
                    if (collectionResourceModels.size() > 0) {
                        for (int i = 0; i < collectionResourceModels.size(); i++) {
                            if (collectionResourceModels.get(i).getId() == resourceId) {
                                collectionResourceModels.remove(collectionResourceModels.get(i));
                            }
                        }
                    }

                    //如果还有选中的数据，继续上传
                    if (collectionResourceModels.size() > 0) {
                        for (CollectionResourceModel roadModel : collectionResourceModels) {
                            if (roadModel.isSelect()) {
                                resourceId = roadModel.getId();
                                uploadResource(roadModel);
                                break;
                            }
                        }
                    }

                    //刷新列表
                    collectionResourceAdapter.notifyDataSetChanged();
                }
                ToastUtils.show(msg);

                break;
        }
        hidePd();
    }

    @Override
    public void onError(int errcode, int tag, String message) {
        ToastUtils.show(message);
        hidePd();
    }
}